let index = null;
let requestUrl = null;
/**
 * 是否主题表
 */
let themeArray = ["否", "是"];

function addHandler() {
	let rowData = $("#prop_list").treegrid("getSelected");

	if (rowData) {
		let parentId = rowData.children || !rowData.parentId ? rowData.id : rowData.parentId;

		$("#parentId").combobox("setValue", parentId);
	}

	requestUrl = "/prop_category/insert";

	$("#prop_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#prop_list").treegrid("getSelected");
	
	if (rowData) {
		requestUrl = "/prop_category/updateById";

		$("#id").val(rowData.id);
		$("#name").textbox("setValue", rowData.name);
		$("#note").textbox("setValue", rowData.note);
		$("#type").combobox("setValue", rowData.type);
		$("#pxh").numberspinner("setValue", rowData.pxh);
		$("#deep").numberspinner("setValue", rowData.deep);
		$("#isTheme").combobox("setValue", rowData.isTheme);
		$("#orderBy").combobox("setValue", rowData.orderBy);
		$("#parentId").combobox("setValue", rowData.parentId);
		$("#sortField").combobox("setValue", rowData.sortField);
		$("#tableName").combobox("setValue", rowData.tableName);

		$("#prop_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

function deleteHandler() {
	let rowData = $("#prop_list").treegrid("getSelected");

	if (rowData) {
		confirmAction("确认删除选中的数据？", function() {
			ajaxPost("/prop_category/deleteById", {
				id: rowData.id
			}, function(resp) {
				showMsg(resp.message);

				$("#parentId").combobox("reload");
				$("#prop_list").treegrid("reload");
			}, error);
		});
	} else {
		alertMsg("请选择要删除的数据！", "warning");
	}
}

function imageHandler() {
	let rowData = $("#prop_list").treegrid("getSelected");

	if (rowData) {
		$("#categoryId").val(rowData.id);
		$("#img").attr("src", rowData.image);

		$("#upload_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

$(document).ready(function() {

	$("#name").textbox({
		width: 150,
		required: true
	});

	$("#pxh").numberspinner({
		min: 0,
		width: 150,
		required: true
	});

	$("#type").combobox({
		url: "/prop_type/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto"
	});

	$("#parentId").combobox({
		url: "/prop_category/selectByType?type=1",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto"
	});

	$("#tableName").combobox({
		url: "/table/selectAll",
		valueField: "name",
		textField: "name",
		width: 150,
		panelWidth: 280,
		panelHeight: "auto",
		groupField: "tableName",
		onSelect: function (record) {
			if (record) {
				$("#sortField").combobox("reload", {
					tableName: record.name
				});
				$("#orderBy").combobox("reload", {
					tableName: record.name
				});
			}
		}
	});

	$("#sortField").combobox({
		url: "/table_field/selectFields",
		valueField: "name",
		textField: "name",
		width: 150,
		panelWidth: 250,
		panelHeight: "auto",
		groupField: "tableName",
		groupFormatter: function (group) {
			return "<div class='blue ell' title='" + group + "'>" + group + "表</div>"
		}
	});

	$("#orderBy").combobox({
		url: "/table_field/selectFields",
		valueField: "name",
		textField: "name",
		width: 150,
		panelWidth: 250,
		panelHeight: "auto"
	});

	fetchSelect("#isTheme", themeArray, {
		width: 150,
		required: true,
		onSelect: function (record) {
			if (record) {
				let value = parseInt(record.value);

				if (value === 0) {
					$("#orderBy").combobox("disable");
					$("#tableName").combobox("disable");
					$("#sortField").combobox("disable");
				} else {
					$("#orderBy").combobox("enable");
					$("#tableName").combobox("enable");
					$("#sortField").combobox("enable");
				}
			}
		}
	});

	$("#deep").numberspinner({
		min: 1,
		width: 150,
		required: true
	});

	$("#note").textbox({
		width: 380,
		height: 100,
		multiline: true
	});

	$("#prop_dialog").dialog({
		title: "道具分类",
		width: 500,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#prop_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#prop_dialog").dialog("close");

						$("#parentId").combobox("reload");
						$("#prop_list").treegrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#prop_dialog").dialog("close");
				$("#prop_form").form("clear");
			}
		}]
	});

	/******************************************************************************************************/

	fetchUploadFilebox("#prop_list", "/prop_category/upload");

	fetchUploadDialog("/prop_category/updateImageById", function () {
		$("#prop_list").datagrid("reload");
	});

	/******************************************************************************************************/

	$("#theme_table").datalist({
		url: "/prop_category/selectThemes",
		idField: "id",
		valueField: "id",
		textField: "name",
		width: 250,
		height: 317,
		textFormatter: function(value, rowData, rowIndex) {
			let content = "";

			content += "<table style='border-spacing:0;'>";
			content += 	"<tr>";
			content += 		"<td rowspan='2'>";
			content += 			"<img height='50' src='/images/index/logo.png' />";
			content += 		"</td>";
			content += 		"<td>";
			content += 			"表名：<span>" + rowData.name + "</span>";
			content += 		"</td>";
			content += 	"</tr>";

			content += 	"<tr>";
			content += 		"<td>";
			content += 			"排序号：<span>" + rowData.pxh + "</span>";
			content += 		"</td>";
			content += 	"</tr>";
			content += "</table>";

			return content;
		},
		onSelect: function(rowIndex, rowData) {
			if(rowData) {
				$("#rule_list").datagrid("reload", {
					propId: rowData.id
				});
			}
		}
	});

	$("#rule_list").datagrid({
		url: "/filter_condition/selectConditions",
		title: "主题表过滤条件",
		method: "get",
		fitColumns: true,
		width: 435,
		height: 284,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let rowData = $("#theme_table").datalist("getSelected");

				if (rowData) {
					$("#rule_list").datagrid("appendRow", {
						name: null,
						value: 0,
						comparator: null
					});
				} else {
					alertMsg("请选择主题表后操作！", "warning");
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let datagrid = $("#rule_list");

				// 结束编辑
				datagrid.datagrid("endEdit", index);

				let rowData = $("#theme_table").datalist("getSelected");

				if (rowData) {
					let rows = datagrid.datagrid("getRows");
					let data = rows[index];

					data.propId = rowData.id;

					ajaxPost("/filter_condition/save", data, function(resp) {
						showMsg(resp.message);

						$("#prop_tree").tree("reload");
						$("#rule_list").datagrid("reload", {
							propId: rowData.id
						});
					}, error);
				} else {
					alertMsg("请选择一条记录后重试！", "warning");
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let datagrid = $("#rule_list");
				let rowData = datagrid.datagrid("getSelected");

				if (rowData.id) {
					ajaxPost("/filter_condition/deleteById", {
						id: rowData.id
					}, function (resp) {
						showMsg(resp.message);

						let rowIndex = datagrid.datagrid("getRowIndex", rowData);

						datagrid.datagrid("deleteRow", rowIndex);
					}, error);
				} else {
					let rowIndex = datagrid.datagrid("getRowIndex", rowData);

					datagrid.datagrid("deleteRow", rowIndex);
				}
			}
		}],
		onDblClickRow: function (rowIndex, rowData) {
			index = rowIndex;

			let list = $("#rule_list");

			list.datagrid("beginEdit", index);

			/*
			 * 重新加载字段名称下拉框数据
			 */
			// 获取字段名称的行编辑器
			let $editor_ = list.datagrid("getEditor", {
				index: index,
				field: "name"
			});

			// 获取选中的主题表行数据
			let row = $("#theme_table").datalist("getSelected");

			$($editor_.target).combobox("reload", {
				tableName: row.tableName
			});

			window.alert("正在重新加载主题表字段...");
		},
		columns: [[
			{field: "name", title: "字段名称", align: "left", width: 150,
				editor: {
					type: "combobox",
					options: {
						url: "/table_field/selectFields",
						valueField: "name",
						textField: "name",
						panelHeight: "auto"
					}
				}
			},
			{field: "comparator", title: "比较符", align: "center", width: 150,
				editor: {
					type: "combobox",
					options: {
						url: "/value_comparator/selectAll",
						valueField: "id",
						textField: "name",
						panelHeight: "auto"
					}
				},
				formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/value_comparator/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#comparator_" + rowIndex).html(data.express);
						}, error);

						return "<div id='comparator_" + rowIndex + "'></div>";
					} else {
						return "<div class='blue'>无</div>";
					}
				}
			},
			{field: "value", title: "字段值", align: "center", width: 150, editor: "textbox"}
		]]
	});

	$("#table_dialog").dialog({
		title: "配置主题表"
	});

	/******************************************************************************************************/

	$("#prop_tree").tree({
		url: "/prop_category/listTree",
		method: "get",
		lines: true,
		animate: true,
		/*
			很多事件的回调函数需要 'node' 参数，它包括下列属性：
				id：绑定到节点的标识值。
				text：要显示的文本。
				iconCls：用来显示图标的 css class。
				checked：节点是否被选中。
				state：节点状态，'open' 或 'closed'。
				attributes：绑定到节点的自定义属性。
				target：目标的 DOM 对象。
		*/
		onContextMenu: function (e, node) { // 右键点击事件
			e.preventDefault();

			// 显示右键菜单
			$("#mm").menu("show", {
				left: e.pageX,
				top: e.pageY
			});
		}
	});

	$("#mm-insert").click(function() {
		let row = $("#prop_tree").tree("getSelected");

		console.log(row.attributes);
	});

	$("#mm-update").click(function() {
		unopen();
	});

	$("#mm-delete").on("click", function() {
		if (!row.children) {
			$.messager.confirm("提示", "是否确认删除？", function (bool) {
				if (bool) {
					ajaxPost("/prop_category/deleteById", {
						id: row.id,
					}, function (resp) {
						showMsg(resp.message);

						$("#prop_tree").tree("remove", row.target);
						$("#prop_list").treegrid("reload");
					}, error);
				}
			});
		} else {
			unopen();
		}
	});

	$("#tree_dialog").dialog({
		title: "道具分类树",
		width: 300,
		height: 500
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_image * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	$("#prop_list").treegrid({
		url: "/prop_category/listTreeGrid",
		idField: "id",
		treeField: "name",
		lines: true,
		animate: true,
		rownumbers: true,
		fitColumns: false,
		height: height_table,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-filter",
			text: "设置条件",
			handler: function() {
				let rowData = $("#prop_list").treegrid("getSelected");

				if (rowData) {
					if (rowData.isTheme) {
						$("#theme_table").datalist("reload", {
							propId: rowData.id
						});

						$("#table_dialog").dialog("open");
					} else {
						alertMsg("选中的道具类型为非主题表！");
					}
				} else {
					unselected();
				}
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "树化显示",
			handler: function() {
				$("#prop_tree").tree("reload");

				$("#tree_dialog").dialog("open");
			}
		}, "-", imageUpdateButton],
		frozenColumns: [[
			{field: "name", title: "道具名称", align: "left", width: 160},
			{field: "image", title: "道具图片", align: "center", width: 80
				, formatter: function(value) {
					return "<img height='" + size + "' src='" + (value ? value : "/images/blank.png" ) + "' />";
				}
			},
			{field: "type", title: "道具类型", align: "center", width: 100
				, formatter: function(value, rowdata, rowIndex) {
					if (value) {
						ajaxGet("/prop_type/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#type_" + rowdata.id).html(data.name);
						}, error);

						return "<div id='type_" + rowdata.id + "'></div>";
					}
				}
			},
			{field: "pxh", title: "排序号", align: "center", width: 100}
		]],
		columns: [[
			{field: "deep", title: "分类深度", align: "center", width: 100},
			{field: "isTheme", title: "是否主题表", align: "center", width: 100
				, formatter: function(value) {
					if (value) {
						return themeArray[value];
					}
				}
			},
			{field: "note", title: "道具说明", align: "center", width: 300
				, formatter: function(value) {
					if (value) {
						return "<div class='green ell' title='" + value + "'>" + value + "</div>";
					}

					return "/";
				}
			},
			{field: "tableName", title: "数据库表名", align: "center", width: 200
				, formatter: function(value) {
					if (value) {
						return "<div class='blue'>" + value + "</div>";
					}

					return "/";
				}
			},
			{field: "orderBy", title: "排序字段", align: "center", width: 200
				, formatter: function(value) {
					if (value) {
						return "<div class='blue'>" + value + "</div>";
					}

					return "/";
				}
			},
			{field: "sortField", title: "分类字段", align: "center", width: 100
				, formatter: function(value) {
					if (value) {
						return "<div class='blue'>" + value + "</div>";
					}

					return "/";
				}
			}
		]]
	});

});